package com.algorithm.ch2.cjm.math;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by jieming.chen on 2020/7/12
 */
public class IsHappy {
    public static void main(String[] args) {
        IsHappy happy = new IsHappy();
        System.out.println(happy.isHappy(19));
        System.out.println(happy.isHappy(0));
        System.out.println(happy.isHappy(1));
        System.out.println(happy.isHappy(21));
    }

    private Set<Integer> sets = new HashSet<>();

    public boolean isHappy(int n) {
        if (sets.contains(n)) {
            return false;
        }
        sets.add(n);
        int res = 0;
        while (n > 0) {
            res += (n % 10) * (n % 10);
            n = n / 10;
        }
        if (res == 1) {
            return true;
        }
        return isHappy(res);
    }
}
